<template>
  <div class="main-container">
    <!-- 搜索筛选 -->
    <div class="search-filter">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="货品">
          <el-input 
            v-model="searchForm.goodsName" 
            placeholder="请输入货品名称/编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="到期日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="货品批次">
          <el-input 
            v-model="searchForm.batch" 
            placeholder="请输入批次"
            clearable
          />
        </el-form-item>
        <el-form-item label="货品条码">
          <el-input 
            v-model="searchForm.barcode" 
            placeholder="请输入货品条码"
            clearable
          />
        </el-form-item>
        <el-form-item label="货品类型">
          <el-select v-model="searchForm.goodsType" placeholder="请选择" clearable>
            <el-option 
              v-for="item in goodsTypeOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单位">
          <el-select v-model="searchForm.unit" placeholder="请选择" clearable>
            <el-option 
              v-for="item in unitOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="正常" value="正常" />
            <el-option label="即将到期" value="即将到期" />
            <el-option label="已到期" value="已到期" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称">
          <el-select v-model="searchForm.warehouseName" placeholder="请选择" clearable>
            <el-option 
              v-for="item in warehouseOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleExport">导出</el-button>
          <el-button @click="handleRefresh">刷新</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table 
        :data="tableData" 
        :loading="loading"
        @selection-change="handleSelectionChange"
        border
        stripe
        style="width: 100%"
        :scroll-x="true"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" width="80">
          <template #default="{ $index }">
            {{ (pagination.page - 1) * pagination.pageSize + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="goodsCode" label="货品编号" />
        <el-table-column prop="goodsName" label="货品名称" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusType(row.status)" 
              :effect="getStatusEffect(row.status)"
            >
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="goodsType" label="货品类型" />
        <el-table-column prop="specs" label="规格型号" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column prop="warehouseName" label="仓库名称" />
        <el-table-column prop="locationName" label="仓位名称" />
        <el-table-column prop="barcode" label="货品条码" />
        <el-table-column prop="currentStock" label="当前库存" />
        <el-table-column prop="batch" label="批次" />
        <el-table-column prop="productionDate" label="生产日期" />
        <el-table-column prop="expirationDate" label="到期日期" />
        <el-table-column prop="shelfLifeDays" label="保质期(天)" width="100" />
        <el-table-column prop="remainingDays" label="剩余天数" width="100">
          <template #default="{ row }">
            <span :style="{ color: row.remainingDays < 0 ? 'red' : row.remainingDays < 31 ? 'orange' : 'green' }">
              {{ row.remainingDays }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="warningDays" label="预警天数" width="100" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup name="bzq">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useShelfLifeApi } from '/@/api/shelfLife/shelfLife'
import { downloadStreamFile } from '/@/utils/download'

const api = useShelfLifeApi()

const loading = ref(false)
const tableData = ref<any[]>([])
const selectedRows = ref<any[]>([])

// 搜索表单
const searchForm = reactive({
  goodsName: '',
  dateRange: [],
  batch: '',
  barcode: '',
  goodsType: '',
  unit: '',
  status: '',
  warehouseName: ''
})

// 选项数据
const goodsTypeOptions = ref([
  { label: '服装', value: '服装' },
  { label: '食品', value: '食品' },
  { label: '家电', value: '家电' },
  { label: '家具', value: '家具' },
  { label: '化妆品', value: '化妆品' },
  { label: '鞋类', value: '鞋类' },
  { label: '配饰', value: '配饰' },
  { label: '玩具', value: '玩具' },
  { label: '书籍', value: '书籍' },
  { label: '运动器材', value: '运动器材' }
])

const unitOptions = ref([
  { label: '瓶', value: '瓶' },
  { label: '粒', value: '粒' },
  { label: '克', value: '克' },
  { label: '卡', value: '卡' },
  { label: '卷', value: '卷' },
  { label: '斤', value: '斤' },
  { label: '件', value: '件' },
  { label: '盒', value: '盒' }
])

const warehouseOptions = ref([
  { label: '供应商', value: '供应商' },
  { label: '客户', value: '客户' },
  { label: '主仓库', value: '主仓库' },
  { label: '成品仓库', value: '成品仓库' },
  { label: '原料仓库', value: '原料仓库' }
])

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 100
})

// 模拟数据
const mockData = [
  {
    goodsCode: 'HPOH6804',
    goodsName: '苹果手机',
    status: '即将到期',
    goodsType: '服装',
    specs: 'blue 蓝色的',
    unit: '瓶',
    warehouseName: '供应商',
    locationName: '客户',
    barcode: '000545as',
    currentStock: 50,
    batch: 1,
    productionDate: '2025-10-23',
    expirationDate: '2025-10-23',
    shelfLifeDays: 365,
    remainingDays: 20,
    warningDays: 30
  },
  {
    goodsCode: 'HPOH1795',
    goodsName: '电视机',
    status: '已到期',
    goodsType: '食品',
    specs: 'blue 蓝色的',
    unit: '粒',
    warehouseName: '供应商',
    locationName: '客户',
    barcode: '000545as',
    currentStock: 50,
    batch: 2,
    productionDate: '2025-10-23',
    expirationDate: '2025-10-23',
    shelfLifeDays: 365,
    remainingDays: -5,
    warningDays: 30
  },
  {
    goodsCode: 'HPOH3705',
    goodsName: '咖啡机',
    status: '即将到期',
    goodsType: '家电',
    specs: 'blue 蓝色的',
    unit: '克',
    warehouseName: '供应商',
    locationName: '客户',
    barcode: '000545as',
    currentStock: 50,
    batch: 3,
    productionDate: '2025-10-23',
    expirationDate: '2025-10-23',
    shelfLifeDays: 365,
    remainingDays: 15,
    warningDays: 30
  },
  {
    goodsCode: 'HPOH5497',
    goodsName: '空调',
    status: '已到期',
    goodsType: '家具',
    specs: 'blue 蓝色的',
    unit: '卡',
    warehouseName: '供应商',
    locationName: '客户',
    barcode: '000545as',
    currentStock: 50,
    batch: 4,
    productionDate: '2025-10-23',
    expirationDate: '2025-10-23',
    shelfLifeDays: 365,
    remainingDays: -10,
    warningDays: 30
  },
  {
    goodsCode: 'HPOH4558',
    goodsName: '洗衣机',
    status: '正常',
    goodsType: '化妆品',
    specs: 'blue 蓝色的',
    unit: '卷',
    warehouseName: '供应商',
    locationName: '客户',
    barcode: '000545as',
    currentStock: 50,
    batch: 5,
    productionDate: '2025-10-23',
    expirationDate: '2025-10-23',
    shelfLifeDays: 365,
    remainingDays: 60,
    warningDays: 30
  },
  {
    goodsCode: 'HPOH5932',
    goodsName: '电脑',
    status: '即将到期',
    goodsType: '鞋类',
    specs: 'blue 蓝色的',
    unit: '斤',
    warehouseName: '供应商',
    locationName: '客户',
    barcode: '000545as',
    currentStock: 50,
    batch: 6,
    productionDate: '2025-10-23',
    expirationDate: '2025-10-23',
    shelfLifeDays: 365,
    remainingDays: 25,
    warningDays: 30
  },
  {
    goodsCode: 'HPOH2181',
    goodsName: '手表',
    status: '已到期',
    goodsType: '配饰',
    specs: 'blue 蓝色的',
    unit: '件',
    warehouseName: '供应商',
    locationName: '客户',
    barcode: '000545as',
    currentStock: 50,
    batch: 7,
    productionDate: '2025-10-23',
    expirationDate: '2025-10-23',
    shelfLifeDays: 365,
    remainingDays: -15,
    warningDays: 30
  },
  {
    goodsCode: 'HPOH3910',
    goodsName: '钢笔',
    status: '即将到期',
    goodsType: '玩具',
    specs: 'blue 蓝色的',
    unit: '盒',
    warehouseName: '供应商',
    locationName: '客户',
    barcode: '000545as',
    currentStock: 50,
    batch: 8,
    productionDate: '2025-10-23',
    expirationDate: '2025-10-23',
    shelfLifeDays: 365,
    remainingDays: 28,
    warningDays: 30
  },
  {
    goodsCode: 'HPOH9174',
    goodsName: '餐具套装',
    status: '已到期',
    goodsType: '书籍',
    specs: 'blue 蓝色的',
    unit: '瓶',
    warehouseName: '供应商',
    locationName: '客户',
    barcode: '000545as',
    currentStock: 50,
    batch: 9,
    productionDate: '2025-10-23',
    expirationDate: '2025-10-23',
    shelfLifeDays: 365,
    remainingDays: -8,
    warningDays: 30
  },
  {
    goodsCode: 'HPOH8389',
    goodsName: '运动鞋',
    status: '正常',
    goodsType: '运动器材',
    specs: 'blue 蓝色的',
    unit: '粒',
    warehouseName: '供应商',
    locationName: '客户',
    barcode: '000545as',
    currentStock: 50,
    batch: 10,
    productionDate: '2025-10-23',
    expirationDate: '2025-10-23',
    shelfLifeDays: 365,
    remainingDays: 80,
    warningDays: 30
  }
]

// 获取状态标签类型
const getStatusType = (status: string) => {
  switch (status) {
    case '正常':
      return 'success'
    case '即将到期':
      return 'warning'
    case '已到期':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态标签效果
const getStatusEffect = (status: string) => {
  return status === '已到期' ? 'dark' : 'light'
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 调用后端API
    const result = await api.page({
      ...searchForm,
      page: pagination.page,
      pageSize: pagination.pageSize
    })
    
    if (result.data && result.data.result) {
      tableData.value = result.data.result.items || []
      pagination.total = result.data.result.total || 0
    } else {
      // 如果API调用失败，使用模拟数据
      tableData.value = mockData
      pagination.total = 100
    }
  } catch (error) {
    console.error('API调用失败:', error)
    ElMessage.error('加载数据失败，使用模拟数据')
    // 使用模拟数据作为备选
    tableData.value = mockData
    pagination.total = 100
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    goodsName: '',
    dateRange: [],
    batch: '',
    barcode: '',
    goodsType: '',
    unit: '',
    status: '',
    warehouseName: ''
  })
  loadData()
}

// 刷新
const handleRefresh = () => {
  loadData()
}

// 导出
const handleExport = async () => {
  try {
    const result = await api.exportData({
      ...searchForm,
      page: pagination.page,
      pageSize: pagination.pageSize
    })
    
    // 参考客户管理的导出方式
    downloadStreamFile(result)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadData()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadData()
}

// 加载下拉选项数据
const loadDropdownData = async () => {
  try {
    // 加载单位选项 - 使用保质期API
    const unitResult = await api.getUnits()
    if (unitResult.data && unitResult.data.result) {
      unitOptions.value = unitResult.data.result.map((item: any) => ({
        label: item.label || item.name,
        value: item.value || item.id
      }))
    } else {
      // 如果API调用失败，使用默认数据
      unitOptions.value = [
        { label: '台', value: '1' },
        { label: '个', value: '2' },
        { label: '件', value: '3' },
        { label: '箱', value: '4' },
        { label: '包', value: '5' },
        { label: '瓶', value: '6' },
        { label: '盒', value: '7' },
        { label: '套', value: '8' },
        { label: '袋', value: '9' },
        { label: '公斤', value: '10' }
      ]
    }
    
    // 加载仓库选项 - 使用保质期API
    const warehouseResult = await api.getWarehouses()
    if (warehouseResult.data && warehouseResult.data.result) {
      warehouseOptions.value = warehouseResult.data.result.map((item: any) => ({
        label: item.label || item.name,
        value: item.value || item.id
      }))
    } else {
      // 如果API调用失败，使用默认数据
      warehouseOptions.value = [
        { label: '主仓库', value: '主仓库' },
        { label: '成品仓库', value: '成品仓库' },
        { label: '原料仓库', value: '原料仓库' },
        { label: '临时仓库', value: '临时仓库' },
        { label: '冷藏仓库', value: '冷藏仓库' }
      ]
    }
    
    console.log('下拉选项数据加载完成')
  } catch (error) {
    console.error('加载下拉选项数据失败:', error)
    ElMessage.warning('加载选项数据失败，使用默认数据')
    // 使用默认数据作为备选
    unitOptions.value = [
      { label: '台', value: '1' },
      { label: '个', value: '2' },
      { label: '件', value: '3' },
      { label: '箱', value: '4' },
      { label: '包', value: '5' },
      { label: '瓶', value: '6' },
      { label: '盒', value: '7' },
      { label: '套', value: '8' },
      { label: '袋', value: '9' },
      { label: '公斤', value: '10' }
    ]
    warehouseOptions.value = [
      { label: '主仓库', value: '主仓库' },
      { label: '成品仓库', value: '成品仓库' },
      { label: '原料仓库', value: '原料仓库' },
      { label: '临时仓库', value: '临时仓库' },
      { label: '冷藏仓库', value: '冷藏仓库' }
    ]
  }
}

// 页面加载
onMounted(() => {
  loadData()
  loadDropdownData()
})
</script>

<style scoped>
.main-container {
  padding: 20px;
}

.search-filter {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.table-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow-x: auto;
}

.table-container .el-table {
  min-width: 1500px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>

